package com.spzx.product.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.bean.BeanUtils;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.product.domain.*;
import com.spzx.product.domain.dto.ProductSaveDTO;
import com.spzx.product.domain.vo.*;
import com.spzx.product.mapper.*;
import com.spzx.product.service.CategoryService;
import com.spzx.product.service.ProductService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
* @author 老韦
* @description 针对表【product(商品)】的数据库操作Service实现
* @createDate 2024-09-24 14:07:17
*/
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product>
    implements ProductService{
    public static void main(String[] args) {
        System.out.println(IdUtil.getSnowflakeNextId());
    }
    @Resource
    ProductSkuMapper productSkuMapper;

    @Resource
    ProductDetailsMapper productDetailsMapper;

    @Resource
    SkuStockMapper skuStockMapper;

    @Resource
    BrandMapper brandMapper;

    @Resource
    CategoryMapper categoryMapper;

    @Resource
    CategoryService categoryService;

    @Override
    public Page<ProductVO> selectProductList(Page<ProductVO> page, Product product) {
        return baseMapper.selectProductVOList(page,product);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertProductInfo(ProductSaveDTO productSaveDTO) {
        //1、新增到 product表
        productSaveDTO.setStatus(0);
        productSaveDTO.setAuditStatus(0);
        productSaveDTO.setCreateBy(SecurityUtils.getUsername());
        int b = baseMapper.insert(productSaveDTO);
        if (b==0){
            System.out.println("ProductService 52行=============================================");
        }


        //新增之后获取商品id
        Long productId = productSaveDTO.getId();


        //将detaile的信息存入表中
        List<String> detailsImageUrlList = productSaveDTO.getDetailsImageUrlList();

        if (!CollectionUtils.isEmpty(detailsImageUrlList)){ //非空判断
            ProductDetails productDetails = new ProductDetails();
            productDetails.setProductId(productId);//关联id
            productDetails.setId(productId); //将主键 和productId绑定 两者值相同关联
            //这里使用的是 import org.apache.commons.lang3.StringUtils;
            productDetails.setImageUrls(StringUtils.join(detailsImageUrlList,","));
            int insert = productDetailsMapper.insert(productDetails);
            if (insert==0){
                System.out.println("ProductService 67行=============================================");
            }
        }


        //新增到sku表
        List<ProductSku> productSkuList = productSaveDTO.getProductSkuList();
        if (!CollectionUtils.isEmpty(productSkuList)){
            productSkuList.forEach(productSku -> {
                //设置关联属性 商品id
                productSku.setProductId(productId);

                //雪花算法设置spuCode
                String code  = DateUtil.today().replace("-","")+IdUtil.getSnowflakeNextId();
                productSku.setSkuCode(code);


                //spuName + sku规格值
                String skuName = productSaveDTO.getName()+productSku.getSkuSpec();

                productSku.setSkuName(skuName);
                //设置状态
                productSku.setStatus(0);
                productSkuMapper.insert(productSku);

                Long skuId = productSku.getId();
                //通过skuId绑定库存
                SkuStock skuStock = new SkuStock();
                skuStock.setSkuId(skuId);
                skuStock.setStatus(0);
                skuStock.setLockNum(0);
                skuStock.setSkuId(skuId);
                skuStock.setLockNum(0);
                //库存总数
                skuStock.setTotalNum(productSku.getStockNum());
                //可用库存
                skuStock.setAvailableNum(productSku.getStockNum());
                skuStock.setSaleNum(0);
                skuStock.setStatus(0);
                skuStockMapper.insert(skuStock);


            });
        }

        return b;
    }

    @Override
    public ProductDetailVO selectProductDetailVO(Long id) {
        //穿的是商品id 根据商品id查询商品的详细信息
        Product product = baseMapper.selectById(id);

        //创建详细信息对象
        ProductDetailVO productDetailVO = new ProductDetailVO();

        BeanUtils.copyProperties(product,productDetailVO);

        //获取品牌名字
        Long brandId = productDetailVO.getBrandId();
        Brand brand = brandMapper.selectBrandById(brandId);
        productDetailVO.setBrandName(brand.getName());


        //获取123级的名字
        Category category1 = categoryMapper.selectById(productDetailVO.getCategory1Id());
        Category category2 = categoryMapper.selectById(productDetailVO.getCategory2Id());
        Category category3 = categoryMapper.selectById(productDetailVO.getCategory3Id());
        productDetailVO.setCategory1Name(category1.getName());
        productDetailVO.setCategory2Name(category2.getName());
        productDetailVO.setCategory3Name(category3.getName());



        //获取详细图片地址列表
        ProductDetails productDetails = productDetailsMapper.selectById(productDetailVO.getId());
        List<String> list = new ArrayList<>();
        if (productDetails!=null){
            String[] split = productDetails.getImageUrls().split(",");
            list = Arrays.asList(split);
            productDetailVO.setDetailsImageUrlList(list);
        }

        //查询sku商品规格列表
        List<ProductSku> productSkus = productSkuMapper.selectList(Wrappers.lambdaQuery(ProductSku.class).eq(ProductSku::getProductId,productDetailVO.getId()));
        if (!CollectionUtils.isEmpty(productSkus)){
            productDetailVO.setProductSkuList(productSkus);
        }

        return productDetailVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateProductSaveDTO(ProductSaveDTO productSaveDTO) {
        //更新 product
        Product product = new Product();
        BeanUtils.copyProperties(productSaveDTO,product);
        baseMapper.updateById(product);

        //更新detail表
        List<String> detailsImageUrlList = productSaveDTO.getDetailsImageUrlList();

        //先删除 再修改
        productDetailsMapper.deleteById(productSaveDTO.getId());

        if (!CollectionUtils.isEmpty(detailsImageUrlList)){
            ProductDetails productDetails = new ProductDetails();

            productDetails.setProductId(productSaveDTO.getId());
            productDetails.setId(productSaveDTO.getId());

            productDetails.setImageUrls(StringUtils.join(productSaveDTO.getDetailsImageUrlList(),","));


            productDetailsMapper.updateById(productDetails);
        }

        //更新sku
        List<ProductSku> productSkuList = productSaveDTO.getProductSkuList();
        if (!CollectionUtils.isEmpty(productSkuList)){
            for (ProductSku productSku : productSkuList) {
                productSku.setSkuName(productSaveDTO.getName() + productSku.getSkuSpec());

                productSkuMapper.updateById(productSku);

                Long skuId = productSku.getId();
                SkuStock skuStock = skuStockMapper.selectOne(Wrappers.lambdaQuery(SkuStock.class)
                        .eq(SkuStock::getSkuId, skuId)
                        .last("limit 1"));;

                skuStock.setTotalNum(productSku.getStockNum());
                skuStock.setAvailableNum(productSku.getStockNum()-skuStock.getLockNum());

                skuStockMapper.updateById(skuStock);

            }


        }



        return 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchDelete(List<Long> ids) {
        //先查对应sku的主键
        List<ProductSku> productSkus = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().in(ProductSku::getProductId,ids));
        ProductSku productSku = productSkuMapper.selectById(3);
        //通过流将id取出
        List<Long> collect = productSkus.stream().map(ProductSku::getId).collect(Collectors.toList());
        //取出之后删除对应库存
        skuStockMapper.deleteBatchIds(collect);
        //删除 sku对应规格 根据productID
        ids.forEach(id->{
            productSkuMapper.delete(Wrappers.lambdaUpdate(ProductSku.class).eq(ProductSku::getProductId,id));
        });

        //删除 商品表
        baseMapper.deleteBatchIds(ids);

        return 1;
    }

    @Override
    public int updateStatusByid(Long id,Integer status ) {

        baseMapper.update(null,new LambdaUpdateWrapper<Product>().eq(Product::getId, id)
                .set(Product::getStatus, status).set(Product::getUpdateBy, SecurityUtils.getUsername()));
        productSkuMapper.update(null,new LambdaUpdateWrapper<ProductSku>().eq(ProductSku::getProductId,id)
                .set(ProductSku::getStatus,status).set(ProductSku::getUpdateBy,SecurityUtils.getUsername())) ;
        return 1;
    }

    @Override
    public IndexVO selectIndexVO() {
        //查询一级分类
        List<Category> levelOneCates = categoryService.treeSelect(0L);
        //查询销量降序排列的前6条数据：
        List<ProductSku> productSkus = productSkuMapper.selectHotSkus();
        //组装数据
        IndexVO indexVO = new IndexVO();
        indexVO.setCategoryList(levelOneCates);
        indexVO.setProductSkuList(productSkus);

        return indexVO;
    }

    @Override
    public List<ProductSku> selectSkulist(SkuQuery skuQuery) {
      return   baseMapper.selectSkulist(skuQuery);
    }

    @Override
    public ProductSkuDetailsVO selectSkuDetailsVOBySkuId(Long skuId) {
        //组装页面需要的数据返回展示: 用来组装查询到的数据的VO对象
        ProductSkuDetailsVO vo = new ProductSkuDetailsVO();
        CompletableFuture<ProductSku> c1 = CompletableFuture.supplyAsync(() -> {
            //1、根据skuId查询sku数据： sku+ skuPrice
            ProductSku productSku = productSkuMapper.selectById(skuId);
            if (productSku == null) {
                throw new ServiceException("商品数据不存在");
            }
            if (productSku.getStatus() != 1) {
                throw new ServiceException("商品已下架");
            }
            SkuPriceVO skuPriceVO = new SkuPriceVO();
            skuPriceVO.setSkuId(skuId);
            skuPriceVO.setSalePrice(productSku.getSalePrice());
            skuPriceVO.setMarketPrice(productSku.getMarketPrice());

            vo.setProductSku(productSku);
            vo.setSkuPrice(skuPriceVO);

            return productSku;
        });



        CompletableFuture<Void> c2 = CompletableFuture.runAsync(() -> {
            //2、根据skuId查询sku库存数据： skuStock
            SkuStock skuStock = skuStockMapper.selectOne(Wrappers.lambdaQuery(SkuStock.class)
                    .eq(SkuStock::getSkuId, skuId)
                    .last("limit 1"));
            vo.setSkuStockVo(skuStock);
        });



        CompletableFuture<Void> c3 = c1.thenAcceptAsync((productSku) -> {
            //3、根据1查询到的sku的productId查询product数据：product+sliderUrls+ specValues
            Product product = baseMapper.selectById(productSku.getProductId());
            if (product != null) {
                List<String> sliderUrlList = Arrays.asList(product.getSliderUrls().split(","));
                List<SpecValueVO> specValueVOS = JSON.parseArray(product.getSpecValue(), SpecValueVO.class);
                vo.setProduct(product);
                vo.setSliderUrlList(sliderUrlList);
                vo.setSpecValueList(specValueVOS);

            }

        });
        CompletableFuture<Void> c4 = c1.thenAcceptAsync((productSku) -> {
            //4、根据1查询到的sku的productId查询productDetails数据： detailsImageUrls
            ProductDetails productDetails = productDetailsMapper.selectOne(Wrappers.lambdaQuery(ProductDetails.class)
                    .eq(ProductDetails::getProductId, productSku.getProductId())
                    .last("limit 1"));
            if (productDetails != null) {
                vo.setDetailsImageUrlList(Arrays
                        .asList(productDetails
                                .getImageUrls()
                                .split(","))
                );
            }
        });

        CompletableFuture<Void> c5 = c1.thenAcceptAsync((productSku) -> {
            //5、根据1查询到的sku的productId查询它下面所有的sku集合：skuSpecValueMap 只查询上架的商品
            List<ProductSku> productSkus = productSkuMapper.selectList(Wrappers.lambdaQuery(ProductSku.class)
                    .eq(ProductSku::getProductId, productSku.getProductId())
                    .eq(ProductSku::getStatus, 1));
            //  String -> long
            //        Map<String, Long> map = productSkus.stream()
            //                .collect(Collectors.toMap(ProductSku::getSkuSpec, ProductSku::getId));
            //深拷贝(拷贝值)和浅拷贝(引用传递)
            //
            //        Map<String,String> map2 = JSON.parseObject(JSON.toJSONString(map), Map.class);
            Map<String, String> map = new HashMap<>();
            productSkus.forEach(sku -> {
                map.put(sku.getSkuSpec(), sku.getId().toString());
            });

            vo.setSkuSpecValueMap(map);
        });
        CompletableFuture.allOf(c1,c2,c3,c4,c5).join();
        return vo;
    }
}




